/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package p3as.cliente;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.logging.Level;
import java.util.logging.Logger;

public class PhaseConnection implements PhaseLoader {

    String location;
    URL url;
    URLConnection connection;
    
    public void takeConnection() throws IOException{
        try {
            location = "http://localhost:8080/P3AS-Servidor/PhaseServlet";
            url = new URL(location);
            connection = url.openConnection();
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);
            connection.setRequestProperty("Content-Type", "application/x-java-serialized-object");
        } catch (Exception ex) {
            Logger.getLogger(PhaseConnection.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public Drawable loadPhase() {
        try {
            takeConnection();
            OutputStream ostream = connection.getOutputStream();
            ObjectOutputStream o = new ObjectOutputStream(ostream);
            o.writeObject("Next");
            o.flush();
            o.close();
            
            InputStream istream = connection.getInputStream();
            ObjectInputStream s = new ObjectInputStream(istream);
            Drawable drawable;
            drawable = (Drawable) s.readObject();
            s.close();
            return drawable;
        } catch (Exception ex) {
            Logger.getLogger(PhaseConnection.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }
}
